package com.yanyeori.framework.web.http.request.resttemplate;

import com.yanyeori.framework.web.annotation.RestContext;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;

/**
 * @author chenkuan 2024/6/5
 */
@Configuration
public class RestClientHttpRequestConfig {

    @RestContext
    @Autowired(required = false)
    private List<RestTemplate> restTemplates;

    @Bean
    @ConditionalOnMissingBean(name = "restClientHttpRequestInterceptor")
    public RestClientHttpRequestInterceptor restClientHttpRequestInterceptor() {
        return new RestClientHttpRequestInterceptor();
    }

    @Autowired
    public void restInterceptor(RestClientHttpRequestInterceptor restClientHttpRequestInterceptor) {
        if (CollectionUtils.isNotEmpty(restTemplates)) {
            restTemplates.forEach(restTemplate -> restTemplate.setInterceptors(Collections.singletonList(restClientHttpRequestInterceptor)));
        }
    }
}
